package com.qf.controller;


import com.google.inject.internal.cglib.core.$ReflectUtils;
import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.Base64;
import com.qf.util.ResponseUtil;
import com.qf.util.VerifyCodeUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@RestController
@RequestMapping("/admin/auth")
public class DtsAdminAuthController {
    @Autowired
    DtsRoleService dtsRoleService;
    @Autowired
    DtsPermissionService dtsPermissionService;

    @RequestMapping("/info")
    public Object info(){
        //subject就是在shiro中存储的用户对象
        Subject subject = SecurityUtils.getSubject();
        //获取DtsAdmin对象

        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();
        Map<String,Object> data = new HashMap<>();
        //查询角色
        Set<String> roles = dtsRoleService.findRoleByIds(admin.getRoleIds());
        data.put("roles",roles);
        data.put("name",admin.getUsername());
        //查询权限
        Set<String> perms = dtsPermissionService.findRoleByIds(admin.getRoleIds());
        data.put("perms",perms);
        data.put("avatar",admin.getAvatar());
        return ResponseUtil.ok(data);
    }


    @RequestMapping("/login")
    public Object login(@RequestBody Map<String,String> map, HttpSession session){
        //获取请求参数
        String code = map.get("code");
        String username = map.get("username");
        String password = map.get("password");
        String uuid = map.get("uuid");

        //校验验证码
        //从服务端(缓存中)获取生成的验证码
        String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);
        if (code == null || !code.equalsIgnoreCase(cachedCaptcha)){
            return ResponseUtil.fail(-1,"验证码已过期或验证码错误");
        }

        //登录操作
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);

        //subject.login()登录方法
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1,"未知的账户");
        } catch (LockedAccountException e){
            e.printStackTrace();
            return ResponseUtil.fail(-1,"账户已锁定");
        } catch (CredentialsException e){
            e.printStackTrace();
            return ResponseUtil.fail(-1,"密码错误");
        }


        System.out.println(subject.hasRole("超级管理员"));
        System.out.println(subject.isPermitted("admin:category:read"));
        return ResponseUtil.ok(session.getId());
    }


    @GetMapping("/captchaImage")
    public Object captchaImage() throws IOException {
        //1. 生成验证码
        //生成指定位数的验证码
        String code = VerifyCodeUtils.generateVerifyCode(2);
        //创建输出流对象
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        //生成验证码图片
        VerifyCodeUtils.outputImage(111,33,outputStream ,code);
        //把输出流的内容转换为字节数组, 方便传输, 为了安全，要对验证码图片数据进行加密
//        outputStream.toByteArray()

        //唯一标识
        String uuid = UUID.randomUUID().toString();

        //把验证码存储到缓存中
        CaptchaCodeManager.addToCache(uuid, code, 5 );


        Map<String,Object> data = new HashMap<>();
        data.put("img", Base64.encode(outputStream.toByteArray()));
        data.put("uuid",  uuid);

        //这里对应了 前端需要的数据结构
        return ResponseUtil.ok(data);
    }
}
